<template>
  <div class="map-box">
    <d2c-map v-if="option" :option="option" @first-load="mapLoad" />
    <slot />
  </div>
</template>

<script>
import d2cMap from '@c/map'
// import MapboxLanguage from '@mapbox/mapbox-gl-language';
import axios from 'axios'
import { clearGrayBuilding } from '@/utils/handleLayer'
import { getBasemap } from '@/api/basemap'
const Axios = axios.create()
export default {
  components: {
    'd2c-map': d2cMap,
  },
  props: {
    'init-layer': {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      // option: window.BASE_STYLE[0].url,
      option: null,
      //option: "http://t0.tianditu.gov.cn/vec_w/wmts?tk=5b3a89f691e786f2dc2b96a5227de158",
      //option: "https://t1.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=24&TILEROW=11&TILEMATRIX=5&tk=0b79a07d2808103ab84aa56485c331a8",
      baseLayer: 'base-layer',
    }
  },
  beforeCreate() {
    getBasemap().then((res) => {
      if (res.success) {
        this.option =
          res.data.find((i) => i.isDefault === 1).serviceUrl ||
          res.data[0].serviceUrl
      }
    })
  },
  methods: {
    mapLoad(e) {
      this.map = e.target
      window.map = this.map
      if (window.BASE_LAYER) {
        // this.map.setMaxBounds(this.map.getBounds())
        // 绘制基础图层
        // this.showBaseLayer()
      }

      // 添加初始化需要显示的图层
      this.addBaseLayers()
      console.log(this.map.getStyles())
      // this.map.addControl(new MapboxLanguage({defaultLanguage: "zh"}));
      this.$emit('on-load', e)
      this.map.on('zoom', () => {
        if (this.map.getZoom() > 13) {
          this.$emit('timeline-visible', true)
        } else {
          this.$emit('timeline-visible', false)
        }
      })
    },
    showBaseLayer() {
      if (!this.map.getLayer(this.baseLayer)) {
        Axios(window.BASE_LAYER).then((res) => {
          this.map.addLayer({
            id: this.baseLayer,
            type: 'line',
            source: {
              type: 'geojson',
              data: res.data,
            },
            paint: {
              'line-color': '#ccc',
              'line-width': 2,
            },
          })
        })
      }
    },
    addBaseLayers() {
      let layers = this.initLayer
      let visibleLayers = layers.filter((item) => item.visible)
      visibleLayers.forEach((layer) => {
        if (layer.style) {
          this.map.addStyle(layer.id, layer.style, {
            onload: () => {
              // console.log(`添加默认显现图层‘${layer.id}’成功`);
              if (layer.id === window.TIMELINE_STYLE_NAME) {
                this.$emit('timeline-layer-load')
                clearGrayBuilding(this.map)
              }
            },
          })
        }
      })
    },
  },
}
</script>

<style lang="scss">
.map-box {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
